class AcademicPartition < ApplicationRecord
  extend OrderAsSpecified

  belongs_to :parent, class_name: self.name, optional: true
  has_many :children, foreign_key: :parent_id, class_name: self.name

  validates :name, uniqueness: {scope: :parent_id, message: '名称已被使用'},
                   length: {minimum: 2, maximum: 30, message: '名称的长度应在2至50字符之间'}

  before_create :ensure_type
  after_create :create_hierarchy

  private

  def ensure_type
    self.type ||= case parent
      when nil
        College.name
      when College
        Department.name
      when Department
        Grade.name
      when Grade
        Klass.name
    end
  end

  def create_hierarchy
    self.class.connection.execute <<-SQL
      INSERT INTO #{AcademicPartitionHierarchy.table_name} 
                  (ancestor_id, descendant_id, distance)
      SELECT ancestor_id, 
             #{id} AS descendant_id,
             distance + 1 AS distance
      FROM #{AcademicPartitionHierarchy.table_name}
      WHERE descendant_id = #{parent_id || 'NULL'}
      UNION SELECT
        #{id} AS ancestor_id,
        #{id} AS descendant_id,
        0 AS distance
    SQL
  end
end
